package com.example.sicnuaccountingapp.ui.budget

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.sicnuaccountingapp.databinding.ItemCategoryBudgetBinding

class BudgetAdapter : ListAdapter<CategoryBudgetInfo, BudgetAdapter.BudgetViewHolder>(BudgetDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BudgetViewHolder {
        val binding = ItemCategoryBudgetBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return BudgetViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BudgetViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class BudgetViewHolder(
        private val binding: ItemCategoryBudgetBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(budgetInfo: CategoryBudgetInfo) {
            binding.apply {
                categoryName.text = budgetInfo.category.name
                budgetAmount.text = String.format("¥%.2f", budgetInfo.budget.amount)
                budgetRemaining.text = String.format("剩余: ¥%.2f", budgetInfo.remaining)
                budgetProgress.progress = budgetInfo.progress.toInt()

                // 设置图标
                budgetInfo.category.iconResourceId?.let {
                    categoryIcon.setImageResource(it)
                }
            }
        }
    }

    private class BudgetDiffCallback : DiffUtil.ItemCallback<CategoryBudgetInfo>() {
        override fun areItemsTheSame(oldItem: CategoryBudgetInfo, newItem: CategoryBudgetInfo): Boolean {
            return oldItem.budget.budgetId == newItem.budget.budgetId
        }

        override fun areContentsTheSame(oldItem: CategoryBudgetInfo, newItem: CategoryBudgetInfo): Boolean {
            return oldItem == newItem
        }
    }
} 